﻿using System;
using System.Linq;
using System.Reflection;
using ClosedXML.Excel;
using SuppKids.Core.Reporting.Data;
using SuppKids.Resources;

namespace SuppKids.Core.Reporting.Excel
{
	public class SkladMonthlyReportGenerator : ExcelReportGenerator
	{
		protected override void CreateWorkbook(out XLWorkbook workbook, out IXLWorksheet worksheet)
		{
			workbook = new XLWorkbook(Assembly.GetExecutingAssembly().GetManifestResourceStream("SuppKids.Core.Reporting.Excel.Templates.SkladMonthlyReportTemplate.xlsx"));
			worksheet = workbook.Worksheets.FirstOrDefault() ?? workbook.Worksheets.Add(workbook.Worksheets.Count.ToString(this.FormatProvider));
		}

		protected override void CreateContent(IXLWorksheet worksheet, IReportData reportData)
		{
			var data = reportData as SkladMonthlyReportData;
			if (data == null)
			{
				throw new InvalidOperationException("Report data is not valid for this kind of report.");
			}

			var index = 1;
			var rowIndex = 10;

			foreach (var product in data.Products)
			{
				var productsAtStorage = data.ProductsAtStorage.Where(a => a.Product.Id == product.Id).ToArray();

				var row = worksheet.Row(rowIndex++);
				row.Cell("A").Value = index++;
				row.Cell("B").Value = product.Name;
				row.Cell("C").Value = Labels.Label_Kg;
				row.Cell("D").Value = (productsAtStorage.Sum(a => a.ConsumptAmount) / 1000).ToString("F"); //in kilogramms

				foreach (var deliveriesByDate in productsAtStorage.GroupBy(a => a.DeliveryDate.Date))
				{
					var day = deliveriesByDate.Key.Day;
					row.Cell("F").CellRight(day).Value = (deliveriesByDate.Sum(a => a.ConsumptAmount) / 1000).ToString("F"); //in kilogramms
				}
			}

			var range = worksheet.Range(string.Format("A10:AK{0}", rowIndex - 1));
			range.Style.Border.InsideBorder = XLBorderStyleValues.Thin;
			range.Style.Border.BottomBorder = XLBorderStyleValues.Thin;
			range.Style.Font.FontName = "Arial";
			range.Style.Font.FontSize = 8;
			range.Style.Font.Bold = false;
			range.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
			range.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;

			range.Column("B").Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
			worksheet.PageSetup.CenterHorizontally = true;
			worksheet.PageSetup.PagesWide = 1;
			worksheet.PageSetup.PagesTall = 9;
		}
	}
}
